package com.example.onlineeducation.ui.auth

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import com.example.onlineeducation.BuildConfig
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.databinding.LoginActivityBinding
import com.example.onlineeducation.utils.YcLoopCountDown
import com.example.onlineeducation.viewmodel.LoginVM
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.yc.jetpacklib.extension.showToast
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.manager.YcActivityManager
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.utils.YcRegularUtil
import com.yc.jetpacklib.utils.YcRegularUtil.ycRegular
import com.yc.jetpacklib.widget.dialog.YcCommonDialog

/**
 *  登录
 */
class LoginActivity : BaseActivity<LoginActivityBinding>(LoginActivityBinding::inflate) {

    companion object {
        private const val KEY_IS_TOKEN_INVALID = "key_is_token_invalid"
        fun newInstance(context: Context) {
            context.startActivity(Intent(context, LoginActivity::class.java).apply {
                putExtra(KEY_IS_TOKEN_INVALID, false)
            })
        }

        @JvmStatic
        fun newInstanceTokenInvalid(application: Context) {
            application.startActivity(Intent(application, LoginActivity::class.java).apply {
                putExtra(KEY_IS_TOKEN_INVALID, true)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            })
        }
    }

    private val mViewModel: LoginVM by ycViewModels()

    private val mVerifyCodeSendLoop: YcLoopCountDown by YcLoopCountDown.initApply(this, 1000, 60000) {
        mPost.observe {
            if (it < 0) {
                mViewBinding.tvGetVerifyCode.apply {
                    text = "获取验证码"
                    isEnabled = true
                    mVerifyCodeSendLoop.finish()
                }
            } else {
                mViewBinding.tvGetVerifyCode.apply {
                    text = "${it / 1000}秒"
                    isEnabled = false
                }
            }
        }
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .statusBarColor(R.color.transparent)
            .statusBarDarkFont(false)
            .hideBar(BarHide.FLAG_SHOW_BAR)
            .fitsSystemWindows(false)
            .init()
    }

    override fun LoginActivityBinding.initView() {
        val isTokenInvalid = intent.getBooleanExtra(KEY_IS_TOKEN_INVALID, false)
        YcActivityManager.finishOthersActivity(this@LoginActivity)
        if (isTokenInvalid) {
            YcCommonDialog(this@LoginActivity, this@LoginActivity)
                .setMsg("登录信息过期，请重新登录!")
                .setSingleBtnText("确定")
                .showSingle()
        }
        //TODO 测试
        if (BuildConfig.DEBUG) {
            etPhone.setText("18959188096")//TODO

            if (BuildConfig.FLAVOR == "app_test") {
                etPhone.setText("13000000001")
                etPhone.setText("18959188096")

                // etPhone.setText("13045677877")
                //  etPhone.setText("18094012545")
                //  etPhone.setText("13014789365")
                //  etPhone.setText("15042312342")
                //  etPhone.setText("15123541318")
                etVerifyCode.setText("645567")
            }
        }

        tvGetVerifyCode.setOnClickListener {
            checkPhoneNum(etPhone.getText()) {
                mVerifyCodeSendLoop.resetStart(false)
                mViewModel.sendVerifyCode(etPhone.getText())
            }
        }
        tvRegister.setOnClickListener {
          RegisterActivity.newInstance(this@LoginActivity)
        }
        btnLogin.setOnClickListener {
            checkPhoneNumAndVerifyCode(etPhone.getText(), etVerifyCode.getText()) {
                mViewModel.login(etPhone.getText(), etVerifyCode.getText())
            }
        }

        mViewModel.apply {
            mSendVerifyCode.observe {
                //TODO 测试

                it.doSuccess {
                    if (BuildConfig.DEBUG) {
                        etVerifyCode.setText(it.subSequence(it.length - 6, it.length) as String)
                    }
                    showToast("验证码发送成功,请注意查收") }.ycShowNetError("发送验证码失败")
            }
            mLogin.observe {
                it.doSuccess {
                    showToast("登录成功")
                    LoginConfirmActivity.newInstance(this@LoginActivity)
                    finish()
                }.ycShowNetError("登录失败")
            }
        }
    }

    private inline fun checkPhoneNum(phoneNum: String, crossinline success: (() -> Unit)) {
        if (phoneNum.ycRegular(YcRegularUtil.PHONE)) {
            success.invoke()
        } else {
            showToast("请输入正确的手机号")
        }
    }

    private inline fun checkPhoneNumAndVerifyCode(phoneNum: String, verifyCode: String, crossinline success: (() -> Unit)) {
        checkPhoneNum(phoneNum) {
            if (verifyCode.ycIsNotEmpty()) {
                success.invoke()
            } else {
                showToast("请输入正确的验证码")
            }
        }
    }
}